<template>
  <div class="visitor-container">
    <div class="page-header">
      <div class="header-content">
        <h2><el-icon><UserFilled /></el-icon> 访客管理系统</h2>
        <el-button type="info" plain round @click="returnToLogin">
          <el-icon><ArrowLeft /></el-icon> 返回登录
        </el-button>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 访客登记表单 -->
      <el-card class="visitor-form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>访客登记</span>
          </div>
        </template>

        <el-form 
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="auto"
          class="visitor-form"
        >
          <el-row :gutter="24">
            <el-col :xs="24" :sm="12">
              <el-form-item label="访客姓名" prop="visitorName">
                <el-input v-model="form.visitorName" placeholder="请输入访客姓名" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="住户信息" prop="residentNameOrPhone">
                <el-input v-model="form.residentNameOrPhone" placeholder="住户姓名或电话" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="到访事由" prop="purpose">
                <el-select v-model="form.purpose" placeholder="请选择到访事由" style="width: 100%">
                  <el-option label="探亲访友" value="visit" />
                  <el-option label="快递配送" value="delivery" />
                  <el-option label="维修服务" value="repair" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="访问时间" prop="visitTime">
                <el-date-picker
                  v-model="form.visitTime"
                  type="datetime"
                  placeholder="选择访问时间"
                  :disabledDate="disabledDate"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="预计离开" prop="leaveTime">
                <el-date-picker
                  v-model="form.leaveTime"
                  type="datetime"
                  placeholder="选择预计离开时间"
                  :disabledDate="disabledDate"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item class="form-buttons">
            <el-button type="primary" @click="submitForm" :loading="loading" round>
              提交登记
            </el-button>
            <el-button @click="resetForm" round>重置表单</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 访客记录 -->
      <el-card class="visitor-history" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>访客记录</span>
            <div class="search-box">
              <el-input
                v-model="searchPhone"
                placeholder="输入手机号查询"
                style="width: 200px"
                clearable
                size="small"
              />
              <el-button 
                type="primary" 
                @click="searchVisitorRecord" 
                :loading="loading"
                size="small"
                round
              >
                查询
              </el-button>
            </div>
          </div>
        </template>

        <el-table 
          :data="visitorHistory" 
          style="width: 100%" 
          v-loading="loading"
          stripe
          size="small"
        >
          <el-table-column prop="visitorName" label="访客姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="purpose" label="到访事由" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getPurposeText(row.purpose) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="visitTime" label="访问时间" width="160" />
          <el-table-column prop="leaveTime" label="预计离开" width="160" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, ArrowLeft } from '@element-plus/icons-vue'
import { registerVisitor, queryVisitorByPhone } from '@/api/api'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 添加返回登录方法
const returnToLogin = () => {
  router.push('/login')
}

// 表单数据
const form = reactive({
  visitorName: '',
  phone: '',
  residentNameOrPhone: '',
  purpose: '',
  visitTime: '',
  leaveTime: ''
})

// 表单验证规则
const rules = {
  visitorName: [
    { required: true, message: '请输入访客姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  residentNameOrPhone: [
    { required: true, message: '请输入住户姓名或电话', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请选择到访事由', trigger: 'change' }
  ],
  visitTime: [
    { required: true, message: '请选择访问时间', trigger: 'change' }
  ],
  leaveTime: [
    { required: true, message: '请选择预计离开时间', trigger: 'change' }
  ]
}

// 访客记录
const visitorHistory = ref([])

// 日期限制
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的日期
}

// 获取到访事由文本
const getPurposeText = (purpose) => {
  const purposes = {
    visit: '探亲访友',
    delivery: '快递配送',
    repair: '维修服务',
    other: '其他'
  }
  return purposes[purpose] || purpose
}

// 获取状态文本
const getStatusText = (status) => {
  const statuses = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'COMPLETED': '已完成'
  }
  return statuses[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    'PENDING': 'info',     // 待审核使用蓝色
    'APPROVED': 'success', // 通过使用绿色
    'REJECTED': 'danger'   // 拒绝使用红色
  }
  return types[status] || 'info'
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const requestData = {
          visitor: {
            name: form.visitorName,
            phoneNumber: form.phone,
            purpose: form.purpose,
            arrivalTime: form.visitTime,
            departureTime: form.leaveTime
          },
          residentNameOrPhone: form.residentNameOrPhone
        }
        const response = await registerVisitor(requestData)
        if (response.code === 200) {
          ElMessage.success('访客登记提交成功，请等待审核')
          const phoneNumber = form.phone
          resetForm()
          searchPhone.value = phoneNumber
          searchVisitorRecord()
        } else {
          ElMessage.error(response.message || '提交失败，请重试')
        }
      } catch (error) {
        ElMessage.error('提交失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 查询用的手机号
const searchPhone = ref('')

// 查询访客记录
const searchVisitorRecord = async () => {
  if (!searchPhone.value) {
    ElMessage.warning('请输入手机号码')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(searchPhone.value)) {
    ElMessage.warning('请输入正确的手机号码')
    return
  }

  try {
    loading.value = true
    const response = await queryVisitorByPhone({ phoneNumber: searchPhone.value })
    if (response.code === 200) {
      visitorHistory.value = response.data.map(visitor => ({
        visitorName: visitor.name,
        phone: visitor.phoneNumber,
        purpose: visitor.purpose,
        visitTime: visitor.arrivalTime,
        leaveTime: visitor.departureTime,
        status: visitor.approvalStatus,
        remark: visitor.remark || ''
      }))
    } else {
      ElMessage.error(response.message || '查询访客记录失败')
    }
  } catch (error) {
    ElMessage.error('查询访客记录失败')
    visitorHistory.value = []
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.visitor-container {
  padding: 24px;
  max-width: 1280px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-wrapper {
  display: grid;
  gap: 24px;
}

.visitor-form-card,
.visitor-history {
  border-radius: 8px;
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-weight: 500;
  color: #444;
}

.visitor-form {
  padding: 16px 0;
}

.form-buttons {
  margin-top: 16px;
  text-align: right;
}

.search-box {
  display: flex;
  gap: 8px;
  align-items: center;
}

.el-table {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .visitor-container {
    padding: 16px;
  }

  .page-header h2 {
    font-size: 20px;
  }

  .content-wrapper {
    gap: 16px;
  }

  .search-box {
    width: 100%;
    margin-top: 12px;
    flex-wrap: wrap;
  }

  .search-box .el-input {
    width: 100%;
    margin-bottom: 8px;
  }
}

@media (max-width: 480px) {
  .form-buttons {
    text-align: center;
  }
  
  .form-buttons .el-button {
    width: 100%;
    margin: 8px 0;
  }
}
</style>